"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 数据库系统
Case Name   : 套接字文件无权限，暂停数据库进程（接收kill -19信号）
Create At   : 2020/07/27
@zou_jialiang0505328126
Description :
    1. 获取套接字文件路径
    2. 获取套接字文件名
    3. 修改套接字文件权限为不可读不可写
    4. 获取pid
    5. 停止数据库进程
    6. 连接数据库
    7. 恢复数据库进程
    8. 连接数据库
    9. 运行tpcc指令
    10. 恢复socket文件权限
    11. 连接数据库
Expect      :
    1. 返回套接字文件路径：
    unix_socket_directory
    -----------------------
     /opt/gaussdb/tmp
    (1 row)
    2. 返回套接字文件名
    .s.PGSQL.15000
    3. 无返回信息
    4. 返回pid
    5850
    5. 无返回信息
    6. 非socket连接连接失败：gsql: wait 10.29.180.204:15000 timeout expired, errno: Success
    Socket连接连接失败：failed to connect Unknown:15000.
    7. 无返回信息
    8. 非socket连接连接成功：postgres=>
    Socket连接连接失败：failed to connect Unknown:15000.
    9. 运行正常，返回信息中关注
    Term-00, Measured tpmC (NewOrders) = 32152.0
    10. 无返回
    11. 非socket连接连接成功：postgres=>
    Socket连接连接成功：postgres#
History     :
    modified: 2022/3/16 @wan005 优化异常恢复步骤
"""
import os
import unittest
from yat.test import Node
import time
from yat.test import macro
import sys

sys.path.append(sys.path[0] + "/../")
from testcase.utils.Logger import Logger
from testcase.utils.Constant import Constant
from testcase.utils.Common import Common
from testcase.utils.CommonSH import *
from testcase.utils.ComThread import ComThread

logger = Logger()
common = Common()
Constant = Constant()


class Stop_immediate(unittest.TestCase):
    dbPrimaryUserNode = Node(node='PrimaryDbUser')
    dbPrimaryRootNode = Node(node='PrimaryRoot')
    DB_INSTANCE_PATH = macro.DB_INSTANCE_PATH
    DB_ENV_PATH = macro.DB_ENV_PATH
    GS_CTL_STOP_SUCCESS_MSG = Constant.GS_CTL_STOP_SUCCESS_MSG
    STANDBY_NORMAL = Constant.STANDBY_NORMAL
    PRIMARY_NORMAL = Constant.PRIMARY_NORMAL
    START_SUCCESS_MSG = Constant.START_SUCCESS_MSG
    TPCC_SUCCESS_MSG = Constant.TPCC_SUCCESS_MSG
    RESTART_SUCCESS_MSG = Constant.RESTART_SUCCESS_MSG
    TPCC_PATH = macro.TPCC_PATH
    file_name = ''
    primary_sh = CommonSH('PrimaryDbUser')
    standby_1_sh = CommonSH('Standby1DbUser')
    standby_2_sh = CommonSH('Standby2DbUser')
    nodes_tuple = ('PrimaryDbUser', 'Standby1DbUser', 'Standby2DbUser')

    @RestartDbCluster(*nodes_tuple)
    def setUp(self):
        logger.info("-----------this is setup-----------")
        logger.info(f"-----{os.path.basename(__file__)[:-3]} start-----")
        self.pid = ''

    def test_stop_immediate(self):
        logger.info("----------------------get socket file path--------------")
        time.sleep(30)
        sql = "show unix_socket_directory"
        getfilepathMsg = self.primary_sh.executDbSql(sql)
        logger.info(getfilepathMsg)
        file_path = getfilepathMsg.split('\n')[2]
        logger.info(file_path)

        logger.info("----------------------get socket file name--------------")
        get_file_list_cmd = f'ls -a {file_path}'
        logger.info(get_file_list_cmd)
        file_list = self.dbPrimaryUserNode.sh(get_file_list_cmd).result()
        logger.info(file_list)
        socket_file_name = ''
        for file in file_list.split():
            logger.info(file)
            if (self.dbPrimaryUserNode.db_port not in file) or ('lock' in file):
                pass
            else:
                socket_file_name = file
        logger.info(socket_file_name)
        self.file_name = file_path + "/" + socket_file_name
        logger.info("------------------modify file permission----------------------")
        deleteCmd = f'chmod 000 {self.file_name}'
        self.dbPrimaryRootNode.sh(deleteCmd).result()
        logger.info(deleteCmd)

        logger.info("-----------------------get pid-------------------------------")
        getPidCmd = 'lsof -i:{port}'.replace('{port}', self.dbPrimaryRootNode.db_port)
        pidMsg = self.dbPrimaryRootNode.sh(getPidCmd).result()
        self.pid = common.getPidFromCmd(str(pidMsg))
        logger.info("-----------------------stop pid-------------------------------")
        stopCmd = f'kill -19 {self.pid}'
        logger.info(stopCmd)
        self.dbPrimaryRootNode.sh(stopCmd)

        logger.info("----------------------connect opengauss----------------------")
        nosocketConnect = ComThread(self.primary_sh.nosocketConnect, args=())
        nosocketConnect.setDaemon(True)
        nosocketConnect.start()

        socketConnect = ComThread(self.primary_sh.socket_connect, args=(file_path,))
        socketConnect.setDaemon(True)
        socketConnect.start()

        nosocketConnect.join(60 * 5)
        no_socket_connect_msg = nosocketConnect.get_result()
        logger.info('no_socket_connect_msg:' + str(no_socket_connect_msg))
        self.assertIsNone(no_socket_connect_msg)

        socketConnect.join(60 * 5)
        socket_connect_msg = socketConnect.get_result()
        logger.info('socket_connect_msg:' + str(socket_connect_msg))
        self.assertIn(Constant.FAILED_CONNECT_DB, socket_connect_msg)

        logger.info("-----------------------reconnect pid-------------------------------")
        reconnect_cmd = f'kill -18 {self.pid}'
        logger.info(reconnect_cmd)
        self.dbPrimaryRootNode.sh(reconnect_cmd)
        time.sleep(60)

        logger.info("----------------------connect opengauss----------------------")
        no_socket_connect_msg = self.primary_sh.nosocketConnect()
        logger.info(no_socket_connect_msg)
        self.assertEqual(no_socket_connect_msg, '')
        self.pid = ''

        socket_connect_msg = self.primary_sh.socket_connect(file_path)
        logger.info(socket_connect_msg)
        self.assertIn(Constant.FAILED_CONNECT_DB, socket_connect_msg)

        logger.info("---------------------start TPCC----------------------")
        tpcc_result = common.startTPCC(self.dbPrimaryRootNode, self.TPCC_PATH)
        logger.info('-------------' + tpcc_result + '-----------------------')
        logger.info(tpcc_result)
        self.assertTrue(tpcc_result.find(self.TPCC_SUCCESS_MSG) > -1)

        logger.info("------------------------recover socket file------------------")
        recover_cmd = f'chmod 600 {self.file_name}'
        logger.info(recover_cmd)
        self.dbPrimaryRootNode.sh(recover_cmd)

        logger.info("----------------------connect opengauss----------------------")
        no_socket_connect_msg = self.primary_sh.nosocketConnect()
        logger.info(no_socket_connect_msg)
        self.assertEqual(no_socket_connect_msg, '')

        socket_connect_msg = self.primary_sh.socket_connect(file_path)
        logger.info(socket_connect_msg)
        logger.info(type(socket_connect_msg))
        self.assertEqual(socket_connect_msg, '')

    def tearDown(self):
        logger.info('----------------this is tearDown-----------------------')
        logger.info("------------------------recover socket file------------------")
        recoverCmd = f'chmod 600 {self.file_name}'
        logger.info(recoverCmd)
        self.dbPrimaryRootNode.sh(recoverCmd)
        if self.pid != '':
            reconnect_cmd = f'kill -18 {self.pid}'
            logger.info(reconnect_cmd)
            self.dbPrimaryRootNode.sh(reconnect_cmd)
            time.sleep(60)

        # 校验刷脏页是否完成
        logger.info('校验刷脏页是否完成')
        dirty_page_finshed_flag = self.primary_sh.check_whether_remain_dirty_page()
        self.assertTrue(dirty_page_finshed_flag)

        # 校验备机是否完成数据同步
        logger.info('校验备机是否完成数据同步')
        flag_1 = self.standby_1_sh.check_data_consistency()
        self.assertTrue(flag_1)
        flag_2 = self.standby_2_sh.check_data_consistency()
        self.assertTrue(flag_2)
